package cn.afei.cloud.controller;

import cn.afei.cloud.config.redis.CacheUtils;
import cn.afei.cloud.config.redis.RedisConstant;
import cn.afei.cloud.utils.result.ResultVOUtils;
import cn.afei.cloud.utils.result.ResultVo;
import jakarta.servlet.http.HttpServletRequest;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class GoodController {
    @Value("${server.port}")
    private String serverport;
    @Autowired
    private Redisson redisson;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/buy_goods")
    public ResultVo buy_goods(HttpServletRequest request) throws Exception {
//        String value = UUID.randomUUID().toString() + Thread.currentThread().getName();
        RLock redissonLock = redisson.getLock(RedisConstant.REDIS_LOCK);
        try {
            redissonLock.lock();
//            Boolean flag = redisTemplate.opsForValue().setIfAbsent(RedisConstant.REDIS_LOCK, value, 10L, TimeUnit.SECONDS); //setnx
//            if (!flag) {
//                return ResultVOUtils.success("抢锁失败" + "\t 服务提供端口：" + serverport);
//            }

            String key = "goods:001";
            String result = CacheUtils.get(key);
            int goddNumber = result == null ? 0 : Integer.parseInt(result);
            if (goddNumber > 0) {
                int realNumber = goddNumber - 1;
                CacheUtils.set(key, realNumber + "");
                System.out.println("成功买到商品，库存还剩下" + realNumber + "件" + "\t 服务提供端口：" + serverport);
                return ResultVOUtils.success("成功买到商品，库存还剩下" + realNumber + "件" + "\t 服务提供端口：" + serverport);
            } else {
                System.out.println("商品已经售完/活动结束/调用超时。欢迎下次光临" + "\t 服务提供端口：" + serverport);
            }
            return ResultVOUtils.success("商品已经售完/活动结束/调用超时。欢迎下次光临" + "\t 服务提供端口：" + serverport);
        } finally {
//            if(CacheUtils.hasKey(RedisConstant.REDIS_LOCK) && CacheUtils.get(RedisConstant.REDIS_LOCK).equalsIgnoreCase(value)) {
//                redisTemplate.delete(RedisConstant.REDIS_LOCK);//删锁
//            }
            //使用事务删除key,保持原子性
//            CacheUtils.deleteTransKey(RedisConstant.REDIS_LOCK,value);
            // lua 脚本，摘自官网
//            CacheUtils.delLurKey(RedisConstant.REDIS_LOCK,value);
            //redisson解锁: 还在持有锁的状态，并且是当前线程持有的锁再解锁
            if (redissonLock.isLocked() && redissonLock.isHeldByCurrentThread()) {
                redissonLock.unlock();
            }
        }
    }

}
